package com.example.othree.controller;

import com.example.othree.common.R;
import com.example.othree.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class FileController {
    // 文件上传的保存路径
    @Value("${data.file}")
    private String filePath;

    @Autowired
    FileService fileService;

    // 上传文件
    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 获取文件名
                byte[] bytes = file.getBytes();
                Path path = Paths.get(filePath + "//" + file.getOriginalFilename());
                Files.write(path, bytes);
                return R.ok().message("文件上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                return R.error().message("文件上传失败");
            }
        }
        return R.error().message("文件为空"); // 返回视图名，这里假设你有一个名为uploadStatus的Thymeleaf模板
    }

    // 下载文件
    @GetMapping("/download/{fileName:.+}")
    public R downloadFile(@PathVariable String fileName,HttpServletResponse response) {
        try {
            InputStream inputStream = new FileInputStream(filePath + "//" + fileName);
            response.reset();
            response.setContentType("application/octet-stream");
            String filename = new File(filePath + "//" + fileName).getName();
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
            outputStream.close();
            return R.ok();
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @GetMapping("/dirList")
    public R listFile(@RequestParam int page,
                      @RequestParam int pageSize) {
        try{
            return R.ok().data("fileDatas", fileService.getFileInfosByPage(page, pageSize));
        } catch (IOException e){
            e.printStackTrace();
            return R.error().message("文件地址访问出错");
        }

    }
    @GetMapping("/dirListAll")
    public R listFile() {
        List<String> fileNames;
        try{
            fileNames = fileService.getFileNames();
        } catch (IOException e){
            e.printStackTrace();
            return R.error().message("文件地址访问出错");
        }
        return R.ok().data("fileNames", fileNames);
    }
}
